import sys;
sys.path.append('..');
from by.vaukalak.core.events.EventDispatcher import *;
from by.vaukalak.core.net.socket.SocketEvent import *;

class SocketConnection(EventDispatcher):

    def __init__(self, connection, address):
        EventDispatcher.__init__(self);
        self._connection = connection;
        self._address = address;
        pass;

    def listen(self, nBytes):
        data = self.recv(nBytes);
        if(data == ""):
            self.dispatchEvent(SocketEvent(SocketEvent.CONNECTION_INTERRUPED, self));
        else:
            if(data != None):
                self.dispatchEvent(SocketEvent(SocketEvent.DATA_RECIVED, self, data));

    def recv(self, nBytes):
        try:
            return self._connection.recv(nBytes);
        except:
            return None;

    def send(self, data):
        self._connection.send(data + "#");

    def getConnection(self):
        return self._connection;